package tgc.edu.xzy.service;

import java.io.File;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import tgc.edu.xzy.entity.TbFile;
import tgc.edu.xzy.repository.FileRepository;

@Service
public class FileService {
	@Autowired
	private FileRepository fileDAO;
	private String path;
	private TbFile TbFile model;
	
	public TbFile findById(Integer id) {
		Optional<TbFile> optional = fileDAO.findById(id);
		if(optional.isPresent()) {
			return optional.get();
		}
		return null;
	}
	
	public List<TbFile> findAll(){
		return fileDAO.findAll();
	}

	//添加事务处理
	@Transactional
	public void save(MultipartFile file) {
		//获取客户端上传文件名
		String filename = file.getOriginalFilename();
		//随机生成一个UUID
		String uuid = UUID.randomUUID().toString();
		TbFile model = new TbFile();
		model.setFilename(filename);
		model.setUuid(uuid);
		fileDAO.save(model);
		File path = new File(this.path);
		if(!path.isDirectory()) {
			path.mkdir();
		}
		File saveFile = new File(path, uuid);
		file.transferTo(saveFile);
	}

	public void download(Integer id, HttpServletRequest request, HttpServletResponse response) {
		TbFile model = findById(id);
		String filename = model.getFilename();
		String uuid = model.getUuid();
		File file = new File(path, uuid);
		if(file.exists()) {		//判断文件是否存在
			
		}
	}
}
